package com.atguigu.krp.common.codec;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.krp.common.protocol.ProxyMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.util.CharsetUtil;

import java.util.List;
import java.util.Map;

/**
 * @Description server decoder
 * @author KEIO  on 2022/1/12.
 * @version 1.0
 */
public class ProxyMessageDecoder extends MessageToMessageDecoder<ByteBuf> {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int type = byteBuf.readInt();

        int metaDataLength = byteBuf.readInt(); // 解封装 metadata
        CharSequence metaDataString = byteBuf.readCharSequence(metaDataLength, CharsetUtil.UTF_8);

        JSONObject metaDataJson = JSON.parseObject(metaDataString.toString());
        Map<String, Object> metaData = metaDataJson.toJavaObject(new TypeReference<Map<String, Object>>(){});

        byte[] data = null;
        if(byteBuf.isReadable()) {
            data = ByteBufUtil.getBytes(byteBuf);
        }

        ProxyMessage proxyMessage = new ProxyMessage(); //  从bytebuf中取出各个数据  封装进消息体中
        proxyMessage.setMetaData(metaData);
        proxyMessage.setType(type);
        proxyMessage.setData(data);



    }
}
